<template>
  <div>
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="value"
      :defaultConfig="editorConfig"
      style="height: 400px; overflow-y: auto;"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import { ref, shallowRef, watch, onBeforeUnmount } from 'vue'
// 下面这一行不能删除 import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
import { uploadImage } from '@/api/upload'
import { baseURL } from '@/utils/request'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['update:modelValue'])

const value = ref(props.modelValue) // 本地可写变量
const editorRef = shallowRef(null)
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {}
}

// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  async customUpload(file, insertFn) {
    try {
      const res = await uploadImage(file)
      const url = res.data.url
      let backend = ''
      // 截取baseUrl http://localhost:8000/api/v1
      // 获取主机名和端口号
      if(baseURL.includes('api/v1')){
        const baseUrl = baseURL.split('/api/v1')[0]
        backend = baseUrl + url
      }
      insertFn(backend, '', url)
    } catch (e) {
      alert('图片上传失败')
    }
  }
}

// 父传子：props变化时同步到本地
watch(
  () => props.modelValue,
  (val) => {
    if (val !== value.value) value.value = val
  }
)

// 子传父：本地内容变化时emit
watch(
  value,
  (val) => {
    emit('update:modelValue', val)
  }
)

function handleCreated(editor) {
  editorRef.value = editor
}

onBeforeUnmount(() => {
  if (editorRef.value) editorRef.value.destroy()
})
</script>